<template>
  <a-trigger :trigger="['hover', 'click']" position="rt" v-model:popup-visible="visible">
    <div id="logo" @click="handleIconClick">
      <img alt="Logo" src="../assets/boxy.png" width="36" height="36" />
    </div>
    <template #content>
      <div class="navigatorMenu">
        <a-doption>新建</a-doption>
        <a-doption @click="handlePJClick">项目管理</a-doption>
        <a-doption @click="handlePIPClick">PIP库管理</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleOpenClick">打开文件</a-doption>
        <a-doption @click="handleSaveClick">保存</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleSearchClick">查找</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleOptionsClick">设置</a-doption>
        <a-doption @click="handleTutorialClick">教程</a-doption>
        <a-divider margin="1px" />
        <a-doption @click="handleAboutClick">关于</a-doption>
      </div>
    </template>
  </a-trigger>
  <Settings ref="modal"></Settings>
  <Pip ref="pipModal"></Pip>
  <Pj ref="pjModal"></Pj>
  <FilePanel ref="Filepanel"></FilePanel>
<TutorialDialog ref="tutorialModal"></TutorialDialog>
</template>

<script setup>
import Blockly from 'blockly'
import { ref } from 'vue'
import { useStore } from '../store/store'
import Settings from './Settings.vue'
import Pip from './Pip.vue'
import Pj from './Pj.vue'
import FilePanel from './FilePanel.vue'
import TutorialDialog from './TutorialDialog.vue'
import { pythonGenerator } from 'blockly/python'
import { Notification } from '@arco-design/web-vue';
import { onMounted, onUnmounted } from 'vue'

const visible = ref()
const modal = ref()
const pipModal = ref()
const pjModal = ref()
const store = useStore()
const Filepanel = ref()
const tutorialModal = ref()


function handleIconClick() {
  Blockly.hideChaff()
}

// 新增键盘事件监听
function handleKeyDown(event) {
  if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
    event.preventDefault()
    handleSaveClick()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})

// 修改原有保存方法，添加事件目标检查
function handleSaveClick(event) {
  if (event?.target.tagName === 'INPUT' || event?.target.tagName === 'TEXTAREA') {
    return
  }
  const json = Blockly.serialization.workspaces.save(store.workspaceSvg)
  const text = JSON.stringify(json)
  // 转换为base64
  const base64 = window.btoa(unescape(encodeURIComponent(text)))

  var code = pythonGenerator.workspaceToCode(store.workspaceSvg) || ''
  code = window.btoa(unescape(encodeURIComponent(code)))
  // POST请求/api/save_file，字段path，content, code
  const savePath = localStorage.getItem('currentFilePath') || 'default_path'
  const saveData = {
    path: savePath,
    content: base64,
    code: code
  }

  fetch('/api/save_file', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(saveData)
  })
  .then(response => {
    if (response.ok) {
      console.log('File saved successfully')
      Notification.success({
        title: '保存成功',
        content: '文件已保存成功！'
      })
      //alert('File saved successfully')
    } else {
      console.error('Failed to save file:', response.status)
      Notification.error({
        title: '保存失败',
        content: '文件保存失败！'
      })
    }
  })
  .catch(error => {
    console.error('Error saving file:', error)
    Notification.error({
      title: '保存失败',
      content: '文件保存失败！'
    })
  })
}

function handleOpenClick() {
  Filepanel.value.handleFilePanelClick()
  visible.value = false
}

function handleSearchClick() {
  store.searchVisible = true
  visible.value = false
}

function handleOptionsClick() {
  modal.value.handleClick()
  visible.value = false
}

function handleTutorialClick() {
  tutorialModal.value.handleTutorialClick()
  visible.value = false
}

function handleAboutClick() {
  window.open('https://www.yuque.com/hzsn/boxy')
  visible.value = false
}

function handlePIPClick() {
  pipModal.value.handlePipClick()
  visible.value = false
}

function handlePJClick() {
  pjModal.value.handlePJClick()
  visible.value = false
}
</script>

<style>
#logo {
  position: absolute;
  z-index: 4;
  top: 0;
  left: 0;

  width: 36px;
  height: 36px;
  padding: 12px;

  background-color: var(--color-bg-2);
}

.navigatorMenu {
  overflow: hidden;

  box-sizing: border-box;
  padding: 12px 16px;

  font-size: 14px;
  line-height: 1.5715;
  color: var(--color-text-2);

  background-color: var(--color-bg-popup);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 -2px 5px rgb(0 0 0 / 10%);

  animation: show-dropdown cubic-bezier(0.3, 1.3, 0.3, 1) 400ms forwards !important;

  > li {
    -webkit-tap-highlight-color: transparent;
  }
}

@keyframes show-dropdown {
  0% {
    width: 0;
    height: 0;
  }

  100% {
    width: 150px;
    height: 350px;
  }
}
</style>
